package cn.gx.kevin.config;


import cn.gx.kevin.common.bootenv.SpringContextUtil;
import cn.gx.kevin.common.ui.AdminControllerHelper;
import cn.gx.kevin.common.ui.LanguageMap;
import cn.gx.kevin.common.ui.LanguageStore;
import cn.gx.kevin.common.user.ILoginUserContext;
import cn.gx.kevin.common.user.LoginUser;
import cn.gx.kevin.common.user.UserFunc;
import cn.gx.kevin.common.utils.IRequestInterceptor;
import cn.gx.kevin.common.utils.SysConfigParams;
import cn.gx.kevin.common.utils.UrlInfo;
import cn.gx.kevin.domain.Menu;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 权限拦截器
 */
public class AuthInterceptor  implements IRequestInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);
    ILoginUserContext userContext = null;
    @Override
    public boolean beforeExecute(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) {
        UrlInfo urlInfo = AdminControllerHelper.getControllerAndCmd(httpServletRequest);
        if(urlInfo.getController().equals("/")){
            String loginUrl =  SysConfigParams.getConfig("login_url");
            if(StringUtils.isEmpty(loginUrl)){
                loginUrl =  "/v1/page/login";
            }
            try{
                httpServletRequest.getRequestDispatcher("/" + loginUrl ).forward(httpServletRequest,httpServletResponse);
            }catch (Exception x){}
            return false;
        }
        String controller =  urlInfo.getController();
        String cmd = urlInfo.getCmd();
        boolean isPageQuery =  "page".equals( cmd) || controller.contains("/page/");

        if(isPageQuery){
            // 将语言文件的访问对象设置到setAttribute中
            String lang = SysConfigParams.getConfig("lang");
            LanguageMap languageMap = LanguageStore.getLanguageMap(lang);
            if(languageMap == null){
                logger.info("languageMap is null   ......"+lang);
            }
            Map<String, String> langMap = languageMap.getLangMap();
            httpServletRequest.setAttribute("Lang", langMap);
            // LangThreadHodler.setMap(langMap);
            Map<String, String[]> paramsMap = httpServletRequest.getParameterMap();
            for (Map.Entry<String, String[]> entry : paramsMap.entrySet()) {
                httpServletRequest.setAttribute(entry.getKey(), entry.getValue()[0]);
            }
        }else{
            //开放静态资源访问
            if(controller.equals("/upload/images") || controller.equals("/upload/files")){
                return true;
            }
        }

        //是否是开放api
        boolean canAccess = SysConfigParams.isOpenApi(controller,cmd);
        if(canAccess){
            return  canAccess;
        }
        if(userContext == null){
           Object contextObj = SpringContextUtil.getBean("loginUserCtx");
           userContext = (ILoginUserContext)contextObj;
        }
        LoginUser loginUser = null;
        try {
            loginUser = userContext.getCurrentUser();
        }catch (Exception x){
            logger.error("",x);
        }
        if(loginUser == null){
            if( isPageQuery ){ //页面请求
                String loginUrl = "/v1/page/login";
                String url =  SysConfigParams.getConfig("login_url");
                if(StringUtils.isNotEmpty(url)){
                    loginUrl = url;
                }
                if(loginUrl.equals(urlInfo.getUrl())){
                    return true;
                }
                String script = "<script type=\"text/javascript\"> (function(){window.top.$B.alert('登录过期！') ;setTimeout(()=>{window.top.location.reload();},2000); })();</script>";
                try{
                    AdminControllerHelper.responseText(httpServletResponse,script);
                }catch (Exception x){
                    logger.error("",x);
                }
                return false;
            }
            AdminControllerHelper.responseJson(httpServletResponse,-1,"not login",null);
            return false;
        }
       //是否是不需要权限验证
        canAccess = SysConfigParams.canAccess(controller,cmd);
        if(canAccess){
            return canAccess;
        }
       //是否超级管理员，直接放行
        if(loginUser.isSuperAdmin()){
            return true;
        }
        if(isPageQuery){
            List<Menu>  userMenus = ( List<Menu>)loginUser.getUserData("userMenus");
            String tmpContrl = controller.replaceFirst("/","");
            for(Menu m : userMenus){
                if( tmpContrl.equals( m.getController()) || controller.equals(m.getController())){
                    return  true;
                }
            }
            AdminControllerHelper.responseText(httpServletResponse,"<p style='color:red;'>无访问权限!</p>");
            return false;
        }
        Map<String, List<UserFunc>> authMap = loginUser.getAuthMap();
        List<UserFunc> userFuncs = authMap.get(controller);
        if(userFuncs == null){
            AdminControllerHelper.responseJson(httpServletResponse,99999,"无访问权限!",null);
            return false;
        }
        canAccess = false;
        for(UserFunc func : userFuncs){
            String code = func.getFuncCode();
            if(cmd.equals(code)){
                canAccess = true;
                break;
            }
        }
        if(!canAccess){
            AdminControllerHelper.responseJson(httpServletResponse,99999,"无访问权限!",null);
            return false;
        }
        return true;
    }

    @Override
    public void afterExecute(HttpServletRequest arg0, HttpServletResponse arg1, Exception arg3)  {

    }


}
